package com.example.client.service.impl;

import com.example.client.mapper.ProductMapper;
import com.example.client.service.ProductService;
import com.example.client.domain.Order;
import com.example.client.domain.Product;
import com.example.client.pojo.Code;
import com.example.client.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Result<List<Product>> getProducts() {
        List<Product> products = productMapper.selectProducts();
        if (products == null) {
            return new Result<>(Code.RESPONSE_CODE_FAIL, "当前没有商品");
        }
        List<Product> newProducts = new ArrayList<>();
        for (Product product : products) {
            if (product.getEnable() == 1) {
                newProducts.add(product);
            }
        }
        return new Result<List<Product>> (newProducts, Code.RESPONSE_CODE_SUCCESS, "查询成功");
    }

    @Override
    public Result order(Order order) {
        Order reOrder = productMapper.getOrderByProductIdAndUserName(order.getUsername(), order.getProduct_id());
        if (reOrder == null) {
            productMapper.order(order);
        }
        else {
            order.setCount(order.getCount() + reOrder.getCount());
            productMapper.updateOrderCount(order);
        }
        return new Result<>(Code.RESPONSE_CODE_SUCCESS, "点单成功");
    }

    @Override
    public Result<List<Order>> shoppingCart(String username) {
        List<Order> orders = productMapper.selectOrderByUserName(username);
        if (Objects.isNull(orders)) {
            return new Result<>(Code.RESPONSE_CODE_FAIL, "购物车为空");
        }
        return new Result<List<Order>>(orders, Code.RESPONSE_CODE_SUCCESS, "查询成功");
    }
}
